/** 聊天泡泡渲染 */

import { type BubbleListProps, Attachments } from 'ant-design-x-vue'
import { ref } from 'vue'
import {
  Typography,
  Collapse,
  CollapsePanel,
  Flex,
  Alert,
  Button,
  Space,
  Tooltip,
  message,
} from 'ant-design-vue'
import { CopyOutlined, CheckOutlined } from '@ant-design/icons-vue'
import { Thinking20Filled, Thinking20Regular } from '@vicons/fluent'
import { Icon } from '@vicons/utils'
import { parseText } from './utils'
import markdownit from 'markdown-it'

const md = markdownit({ html: false, breaks: true })

/**
 * 聊天泡泡属性
 *
 * @param data 内容数据
 * @returns
 */
export const renderChatBubbles: BubbleListProps['roles'] = (data) => {
  if (data.role === 'me') {
    return {
      placement: 'end',
      style: {
        marginTop: '20px',
      },
    }
  }
  if (data.role === 'system') {
    return {
      variant: 'borderless',
      placement: 'start',
      messageRender: (content) => <Alert v-show={!!content} type="info" message={content} />,
    }
  }
  if (data.role === 'file') {
    return {
      placement: 'end',
      variant: 'borderless',
      messageRender(items: any) {
        return (
          <Flex vertical gap="middle" style="align-items: flex-end;">
            {items.map((file: any) => (
              <Attachments.FileCard key={file.uid} item={file} />
            ))}
          </Flex>
        )
      },
    }
  }
  // 通过计算是否正在输入中来确认深度思考标签收缩状态
  const isTyping = data.key.toString().startsWith('msg_')
  const activeThink = ref(isTyping ? 'think' : '')
  return {
    placement: 'start',
    variant: 'borderless',
    style: {
      marginTop: '20px',
    },
    messageRender: (content) => {
      // 渲染 markdown 回复
      const response = parseText(content)
      return (
        <Typography class="vas-chat-bubbles">
          <Collapse
            class="chat-think"
            v-show={!!response.think.length}
            v-model:activeKey={[activeThink.value]}
          >
            <CollapsePanel
              key="think"
              header={
                <div class="think-title">
                  {response.content.length ? '已深度思考' : '深度思考中'}
                  <Icon class={response.content.length ? '' : 'icon-thinking'}>
                    <Thinking20Filled />
                    <Thinking20Regular />
                  </Icon>
                </div>
              }
            >
              <div class="text-content" v-html={md.render(response.think)} />
            </CollapsePanel>
          </Collapse>
          <div v-show={!!response.content.length} class="chat-content">
            <div v-html={md.render(response.content)} />
          </div>
          <Alert
            v-show={!!response.error.length}
            class="chat-content error"
            type="error"
            message={<div v-html={md.render(response.error)} />}
            banner
          />
        </Typography>
      )
    },
    footer: (content) => {
      if (!isTyping && typeof content === 'string') {
        const copyed = ref(false)
        const response = parseText(content)
        const text = response.content.replace(/^\n+/, '')
        if (text) {
          const handleCopy = async () => {
            try {
              await navigator.clipboard.writeText(text)
              copyed.value = true
              message.success('复制成功')
              setTimeout(() => {
                copyed.value = false
              }, 3000) // 3秒后重置复制状态
            } catch (error) {
              window.console.error(error)
              message.error('复制失败: ', error.message)
            }
          }
          return (
            <Space>
              <Tooltip title="复制" placement="top">
                <Button
                  type="text"
                  size="small"
                  icon={copyed.value ? <CheckOutlined /> : <CopyOutlined />}
                  onClick={handleCopy}
                />
              </Tooltip>
            </Space>
          )
        }
      }
    },
  }
}
